#include "../common.h"
#ifdef CONFIG_OPEN_P2P__
String AddressTool::toIp(String str, String cmd, char theChar) {
	int addressStartIndex = cmd.length();
	int addressEndIndex = str.lastIndexOf(theChar);
	return str.substring(addressStartIndex, addressEndIndex);
}

String AddressTool::toArg(String str, String cmd) {
	//TODO
	int addressStartIndex = cmd.length();
 	return str.substring(addressStartIndex + 1);
}

int AddressTool::toPort(String str, char theChar) {
	int addressEndIndex = str.lastIndexOf(theChar);
	return str.substring(addressEndIndex + 1).toInt();
}

/**
 * clinet
 * **/
bool UdpWarp::connect() {
	if (udp.connected()) {
		return true;
	}
	return udp.connect(addr, port);
}
/**
 * server
 * 注意 listen() 与 connect() 不能同时调用，原因是共用一个IP
 * 监听本地端口请调用 listen(IPAddress addr, int port)
 *
 * **/
bool UdpWarp::listen() {
	if (udp.connected()) {
		return true;
	}
	return udp.listen(addr, port);
}
bool UdpWarp::listen(IPAddress addr, int port) {
	return udp.listen(addr, port);
}

bool UdpWarp::listen(String addr, int port) {
	IPAddress _a;
	_a.fromString(addr);
	return listen(_a, port);
}

bool UdpWarp::send(std::string msg, IPAddress addr, int port) {
	message.write((uint8_t*) msg.c_str(), msg.size());
	bool ret = udp.sendTo(message, addr, port);
	message.flush();
	return ret;
}
bool UdpWarp::send(std::string msg, String addr, int port) {
	IPAddress _a;
	_a.fromString(addr);
	bool ret = send(msg, _a, port);
	return ret;
}

void UdpWarp::onPacket(AuPacketHandlerFunction cb) {
	udp.onPacket(cb);
}
void UdpWarp::close() {
	if (udp.connected()) {
		udp.close();
	}
}
#endif
